/**
 * MySQL用户重置脚本
 * 用于创建或重置EndoSight-UC系统所需的数据库用户
 */

import mysql from 'mysql2/promise';
import dotenv from 'dotenv';

dotenv.config();

async function resetMySQLUser() {
  let connection = null;

  try {
    console.log('🔄 正在尝试连接MySQL...');

    // 尝试使用不同的常见配置连接
    const connectionConfigs = [
      { host: 'localhost', user: 'root', password: '' },
      { host: 'localhost', user: 'root', password: 'root' },
      { host: 'localhost', user: 'root', password: '123456' },
      { host: 'localhost', user: 'root', password: 'mysql' },
      { host: 'localhost', user: 'mysql', password: '' },
      { host: 'localhost', user: 'mysql', password: 'mysql' }
    ];

    let workingConfig = null;

    for (const config of connectionConfigs) {
      try {
        console.log(`🔍 尝试配置: user=${config.user}, password=${config.password || '空'}`);
        connection = await mysql.createConnection(config);
        console.log('✅ MySQL连接成功!');
        workingConfig = config;
        break;
      } catch (error) {
        console.log(`❌ 配置失败: ${error.message}`);
        if (connection) {
          await connection.end();
          connection = null;
        }
      }
    }

    if (!connection) {
      console.error('❌ 无法连接到MySQL，请检查MySQL服务状态和认证配置');
      console.log('💡 建议:');
      console.log('   1. 确保MySQL服务正在运行');
      console.log('   2. 检查MySQL root用户密码');
      console.log('   3. 尝试重置MySQL root密码');
      return false;
    }

    console.log('🔍 检查数据库是否存在...');

    // 创建数据库（如果不存在）
    await connection.execute('CREATE DATABASE IF NOT EXISTS endo_sight_uc CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci');
    console.log('✅ 数据库 endo_sight_uc 已就绪');

    // 创建应用用户（如果不存在）或更新密码
    const appUser = 'endo_sight_user';
    const appPassword = 'endo_sight_2024_secure';

    try {
      await connection.execute(`CREATE USER IF NOT EXISTS '${appUser}'@'localhost' IDENTIFIED BY '${appPassword}'`);
      await connection.execute(`GRANT ALL PRIVILEGES ON endo_sight_uc.* TO '${appUser}'@'localhost'`);
      await connection.execute('FLUSH PRIVILEGES');
      console.log('✅ 应用用户创建成功');
    } catch (error) {
      console.warn('⚠️ 用户创建警告:', error.message);
    }

    // 测试新用户连接
    console.log('🔍 测试应用用户连接...');
    const testConnection = await mysql.createConnection({
      host: 'localhost',
      user: appUser,
      password: appPassword,
      database: 'endo_sight_uc'
    });

    await testConnection.execute('SELECT 1');
    await testConnection.end();
    console.log('✅ 应用用户连接测试成功');

    // 更新.env文件
    const envContent = `# 数据库配置
DB_HOST=localhost
DB_PORT=3306
DB_USER=${appUser}
DB_PASSWORD=${appPassword}
DB_NAME=endo_sight_uc

# 服务器配置
PORT=4000
NODE_ENV=development

# JWT配置 - P0-A安全修复 - 焦土协议密钥轮换
JWT_SECRET=da469aaf715e0312b2a7411a2515ffc3bd3d8ab63d98d9e7f0215384a07f80ed8aa4f056a60b635318de76e003c9884002e76b00ca2b8ebe3e4027417e945506
JWT_EXPIRES_IN=2h

# 文件上传配置
UPLOAD_PATH=./uploads/medical_images
MAX_FILE_SIZE=10485760
ALLOWED_FILE_TYPES=image/jpeg,image/png,image/dcm,image/bmp

# API限流配置
RATE_LIMIT_WINDOW_MS=60000
RATE_LIMIT_MAX_REQUESTS=10

# TDP-002: AI推理服务配置
# 真实版模型（完整AI推理服务）
AI_INFERENCE_URL=http://localhost:5001/v1/predict

# 调试模式（显示所有状态任务）
DEBUG_SHOW_ALL_TASKS=true

# DeepSeek API配置 - P0-D安全修复 - 焦土协议密钥轮换
# 警告：生产环境请使用官方API密钥
DEEPSEEK_API_KEY=sk-89ce657af94ad395f677590e162fed325011a16dbdfd2ea7
DEEPSEEK_API_URL=https://api.deepseek.com/v1/chat/completions

# 数据库加密配置 - 焦土协议
DB_ENCRYPTION_KEY=59e457903a53500d7190d2c4c2c90f17d74320df963a5163b789132b53fddcd3
DB_ENCRYPTION_ALGORITHM=AES-256-GCM
ADMIN_SECURE_PASSWORD=8f94683e08c9cbc1
`;

    // 写入更新后的.env文件
    const fs = await import('fs');
    fs.writeFileSync('.env', envContent);
    console.log('✅ .env文件已更新');

    await connection.end();

    console.log('🎉 MySQL用户重置完成!');
    console.log('📋 新的数据库配置:');
    console.log(`   用户名: ${appUser}`);
    console.log(`   密码: ${appPassword}`);
    console.log(`   数据库: endo_sight_uc`);

    return true;

  } catch (error) {
    console.error('❌ 重置过程中出错:', error.message);
    if (connection) {
      await connection.end();
    }
    return false;
  }
}

// 运行重置脚本
resetMySQLUser().then(success => {
  if (success) {
    console.log('✅ 可以重新启动后端服务了');
  } else {
    console.log('❌ 重置失败，请手动检查MySQL配置');
  }
  process.exit(success ? 0 : 1);
}).catch(error => {
  console.error('❌ 脚本执行失败:', error);
  process.exit(1);
});